package com.baichang.taoshunda.service.impl;

import com.baichang.framework.excelption.ServiceException;
import com.baichang.taoshunda.dao.BussinessDao;
import com.baichang.taoshunda.dao.RyFriendDao;
import com.baichang.taoshunda.dao.UserDao;
import com.baichang.taoshunda.entity.Bussiness;
import com.baichang.taoshunda.entity.RyFriend;
import com.baichang.taoshunda.entity.User;
import com.baichang.taoshunda.entity.em.FriendState;
import com.baichang.taoshunda.service.RyFriendService;
import com.baichang.taoshunda.utils.RongYunUtils;
import com.google.common.base.Optional;
import net.sf.json.JSONObject;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * Created by ${wushenglu} on 2018/5/21.
 */
@Service
public class RyFriendServiceImpl implements RyFriendService {
    @Autowired
    RyFriendDao ryFriendDao;
    @Autowired
    UserDao userDao;
    @Autowired
    BussinessDao bussinessDao;

    @Override
    public Map<String, Object> invite(String userId, String friendId, String message, String user, String friend) {
        Map<String, Object> map = new HashedMap();
        // 10: 请求, 11: 被请求, 20: 同意, 21: 忽略, 30: 被删除
        String userTrendsId = "";
        String friendTrendId = "";
        if (userId.contains("user") && !userId.equals("")) {
            String id = userId.substring(4, userId.length());
            userTrendsId = Optional.fromNullable(userDao.getEntityById(id).getTrendsUserId()).or("");
        } else if (userId.contains("company") && !userId.equals("")) {
            String id = userId.substring(7, userId.length());
            userTrendsId = Optional.fromNullable(bussinessDao.getEntityById(id).getTrendsUserId()).or("");
        }
        if (friendId.contains("company") && !friendId.equals("")) {
            String id = friendId.substring(7, friendId.length());
            friendTrendId = Optional.fromNullable(bussinessDao.getEntityById(id).getTrendsUserId()).or("");
        } else if (friendId.contains("user") && !friendId.equals("")) {
            System.out.println(friendId);
            String id = friendId.substring(4, friendId.length());
            System.out.println(id);
            friendTrendId = Optional.fromNullable(userDao.getEntityById(id).getTrendsUserId()).or("");
        }
        RyFriend userObject = new RyFriend();
        userObject.setFriendId(friendId);
        userObject.setDisplayName("");
        userObject.setMessage(message);
        userObject.setStatus(FriendState.请求.getCode());
        userObject.setUserId(userId);
        userObject.setDeleteStatus(1);
        userObject.setUser(friend);
        userObject.setTrendsUserId(friendTrendId);
        String spec2 = StringEscapeUtils.unescapeJava(friend);
        friend = spec2.replaceAll("\"\\{", "\\{").replaceAll("\\}\"", "\\}");
        JSONObject friendIfon = JSONObject.fromObject(friend);
        userObject.setHeadPic(friendIfon.get("portraitUri").toString());
        userObject.setNickName(friendIfon.get("nickname").toString());
        ryFriendDao.save(userObject);
        RyFriend friendObiect = new RyFriend();
        friendObiect.setFriendId(userId);
        friendObiect.setDisplayName("");
        friendObiect.setMessage(message);
        friendObiect.setTrendsUserId(userTrendsId);
        friendObiect.setStatus(FriendState.被请求.getCode());
        friendObiect.setUserId(friendId);
        friendObiect.setDeleteStatus(1);
        String user2 = StringEscapeUtils.unescapeJava(user);
        user = user2.replaceAll("\"\\{", "\\{").replaceAll("\\}\"", "\\}");
        JSONObject userInfo = JSONObject.fromObject(user);
        friendObiect.setHeadPic(userInfo.get("portraitUri").toString());
        friendObiect.setNickName(userInfo.get("nickname").toString());
        friendObiect.setUser(user);
        ryFriendDao.save(friendObiect);
        map.put("action", "Added");
        return map;
    }

    @Override
    public boolean agree(String userId, String friendId) {

        return ryFriendDao.agree(userId, friendId, FriendState.同意.getCode()) > 0;
    }

    @Override
    public boolean ignore(String userId, String friendId) {
        return ryFriendDao.agree(userId, friendId, FriendState.忽略.getCode()) > 0;
    }

    @Override
    public boolean delete(String userId, String friendId) {
        return ryFriendDao.agree(userId, friendId, FriendState.被删除.getCode()) > 0;
    }

    @Override
    public boolean setDisplayName(String friendId, String displayName, String userId) {

        return ryFriendDao.setDisplayName(friendId, displayName, userId);
    }

    @Override
    public List<Map<String, Object>> all(String userId, Integer nowPage, Integer pageSize) {

        return ryFriendDao.all(userId, nowPage, pageSize);
    }

    @Override
    public Map<String, Object> profile(String friendId, String userId) {

        return ryFriendDao.profile(friendId, userId, 1);
    }

    @Override
    public List<Map<String, Object>> inviteAllList(String userId, Integer nowPage, Integer pageSize, Integer friendShipStatus) {
        return ryFriendDao.inviteAllList(userId, nowPage, pageSize, friendShipStatus);
    }

    @Override
    public Map<String, Object> checkIsFriend(String friendId, String userId) {
        Map map = new HashedMap();
        Map<String, Object> friend = ryFriendDao.profile(friendId, userId, 1);
        if (friend == null || friend.isEmpty() || friend.size() == 0) {
            map.put("isFriend", true);
            map.put("status", 0);
            ryFriendDao.deleteByUserId(userId, friendId);
            ryFriendDao.deleteByUserId(friendId, userId);
        } else {
            map.put("isFriend", false);
            map.put("status", friend.get("status"));
        }
        return map;
    }

    @Override
    public Object getUserInfoByUserId(String userId, String selfUserId) throws ServiceException {
        String returnUserInfo = RongYunUtils.getUserInfo(userId);
        JSONObject jsonObject = JSONObject.fromObject(returnUserInfo);
        if (userId.contains("user") && !userId.equals("")) {
            String id = userId.substring(4, userId.length());
            User user = userDao.getEntityById(id);
            if (user != null) {
                jsonObject.put("trendsUserId", user.getTrendsUserId());
                jsonObject.put("sex", user.getSex());
            }
        } else if (userId.contains("company") && !userId.equals("")) {
            String id = userId.substring(7, userId.length());
            Bussiness bussiness = bussinessDao.getEntityById(id);
            if (bussiness != null) {
                jsonObject.put("trendsUserId", bussiness.getTrendsUserId());
                jsonObject.put("sex", bussiness.getSex());
            }
        }
        if (userId.equals(selfUserId)) {
            jsonObject.put("displayName", "");
        } else {
            RyFriend ryFriend = ryFriendDao.getFriend(userId, selfUserId);
            if (ryFriend != null) {
                jsonObject.put("displayName", ryFriend.getDisplayName());
            } else {
                jsonObject.put("displayName", "");
            }

        }
        return jsonObject;
    }

    @Override
    public List<Map<String, Object>> findFriendsByAccount(String userId, String telPhone) {
        List<Map<String, Object>> list = ryFriendDao.getListByAccount(telPhone);
        for (int i = 0; i < list.size(); i++) {
            Map map = list.get(i);
            String friendId = JSONObject.fromObject(map.get("ryToken")).get("userId").toString();
            map.put("token", JSONObject.fromObject(map.get("ryToken")).get("token"));
            map.put("friendId", friendId);
            Map<String, Object> friend = ryFriendDao.profile(friendId, userId, 1);
            if (friend == null || friend.isEmpty() || friend.size() == 0) {
                map.put("isFriend", true);
                map.put("status", 0);
                ryFriendDao.deleteByUserId(userId, friendId);
                ryFriendDao.deleteByUserId(friendId, userId);
            } else {
                map.put("isFriend", false);
                map.put("status", friend.get("status"));
            }
        }
        return list;
    }

    @Override
    public boolean deleteHistory(Integer id) {

        return ryFriendDao.deleteHistory(id);
    }

    @Override
    public void updateHeadPic(String userId, String headPic, String sex, String name) {
        ryFriendDao.updateHeadPic(userId, headPic, sex, name);
    }

    /**
     * 通过设置的备注   源用户的昵称  账号模糊查询
     *
     * @param userId 用户聊天编号
     * @param key    关键字
     * @return
     */
    @Override
    public List<Map<String, Object>> findFriend(String userId, String key) {
        if (key.equals("")) {
            return new ArrayList<>();
        }
        return ryFriendDao.findFriend(userId, key);
    }

}
